package com.yourannet.utils;

import java.io.File;
import java.io.IOException;

import com.yourannet.android.R;
import com.yourannet.android.commons.Alert;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public  class SpeakControl  {
	
	private Activity m_activity=null;
	public SpeakControl(){}  
	/**
	 * 初始化录音控件
	 * @param activity
	 */
	public SpeakControl (Activity activity){
		m_activity=activity;
		// 是否存在SD卡
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			//home =new File( Environment.getExternalStorageDirectory().getAbsoluteFile()+File.separator+"cgt_data_support"+File.separator+"videoData");
			home=new File("/sdcard/cgt_data_support/videoData/");
			if(!home.exists()){
		    	home.mkdirs();
		    }
			init();
		} else {
			Toast.makeText(m_activity, "请先插入SD卡", Toast.LENGTH_LONG).show();
			return;
		}
	}
	
	Button  m_btnStop, m_btn_play;
	private Button m_btnOk,m_btnCancel;
	ImageButton m_btnStar;
	private MediaRecorder mMediaRecorder = null;
	//private File home = null;
	private File home =new File("/sdcard/cgt_data_support/videoData/");
	private File path = null;
	private String temp = "recaudio_";
	private String TAG = "SpeakControl";

	
	// 声音控制
	Alert alertSoundBox = null;
	CheckBox m_ckAudio = null, m_ckAudioPlay = null;
	View m_microphoneing = null, m_microphone = null, m_microphone_exit = null;
	TextView m_media_state = null;
	
	MediaPlayer m_mediaPlayer=null;
	

	private  void init(){
		//声音控件
		alertSoundBox = new Alert(m_activity, -2, -2, R.layout.speak_box);
		View view = alertSoundBox.getDialogView();
		m_ckAudio = (CheckBox) view.findViewById(R.id.ck_record);
		m_ckAudio.setChecked(false);
		m_ckAudio.setOnClickListener(audioListener);
		m_btnOk = (Button)view.findViewById(R.id.record_ok);
		m_btnOk.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(m_activity, "录音完毕！", Toast.LENGTH_LONG).show();
				release();
				alertSoundBox.close();
				if (null != m_ckAudio && m_ckAudio.isChecked()) {
					m_ckAudio.setChecked(false);
				}
			}
			
		});
		m_btnCancel = (Button)view.findViewById(R.id.record_cancel);
		m_btnCancel.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(m_activity, "取消本次录音！", Toast.LENGTH_LONG).show();
				release();
				alertSoundBox.close();
				if (null != m_ckAudio && m_ckAudio.isChecked()) {
					m_ckAudio.setChecked(false);
				}
			}
			
		});
		m_ckAudioPlay = (CheckBox) view.findViewById(R.id.ck_play);
		m_ckAudioPlay.setOnClickListener(audioListener);

		m_microphoneing = view.findViewById(R.id.microphoneing);
		m_microphone = view.findViewById(R.id.microphone_static);
		m_microphone_exit = view.findViewById(R.id.dialog_exit);
		m_microphone_exit.setOnClickListener(audioListener);
		m_media_state = (TextView) view.findViewById(R.id.media_state);

		m_activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		
	}
	
	
	/**
	 * 开始录音
	 */
	public void startRecord(){
		try {
			 
			// 创建录音临时文件
			//path=new File(home+File.separator+"cgt_data_support"+File.separator+"videoData"+File.separator+"video.amr");
			path = File.createTempFile(temp, ".3gp", home);//支持  .amr |.wav
			//setTitle("==" + path.getAbsolutePath());
		
				mMediaRecorder = new MediaRecorder();
			
				mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置数据来源，麦克风
				mMediaRecorder
						.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);// 设置格式
				mMediaRecorder
						.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// 设置编码
			
				mMediaRecorder.setOutputFile(path.getAbsolutePath());// 设置输出文件路径
			
				
			mMediaRecorder.prepare();
			mMediaRecorder.start();
		} catch (IOException e) {
			mMediaRecorder.release();
			e.printStackTrace();
		}catch(OutOfMemoryError error){
			cgt.jni.business.LogMgr.GetInstance().writeLog("OutOfMemoryError from  SpeakControl line 75");
		}catch(Exception ex){
			cgt.jni.business.LogMgr.GetInstance().writeLog("Exception from  SpeakControl line 77");
		}
	}
	
	/**
	 * 结束录音
	 */
	public void stopRecord(){
		if(mMediaRecorder==null){
			return;
		}
		
		try{
		mMediaRecorder.stop();
		mMediaRecorder.release();
		mMediaRecorder = null;
		onRecordCompletion(path.getAbsolutePath());
		}
		catch(OutOfMemoryError error){
			cgt.jni.business.LogMgr.GetInstance().writeLog("OutOfMemoryError from  SpeakControl line 96");
		}catch(Exception ex){
			mMediaRecorder.release();//释放资源
			cgt.jni.business.LogMgr.GetInstance().writeLog("Exception from  SpeakControl line 99");
		}
	}
	
	/**
	 * 暂停
	 */
	public void suspend(){
		
		try{
			if(m_mediaPlayer!=null){
				m_mediaPlayer.pause();
			}
		}catch(OutOfMemoryError error){
			cgt.jni.business.LogMgr.GetInstance().writeLog("OutOfMemoryError from  SpeakControl line 113");
		}catch(Exception ex){
			m_mediaPlayer.release();
			cgt.jni.business.LogMgr.GetInstance().writeLog("OutOfMemoryError from  SpeakControl line 116");
		}
		
	}
	/**
	 * 释放资源
	 */
	public void release(){
		setAudioState(false);
		
		try{
		if(m_mediaPlayer!=null){
			m_mediaPlayer.release();
		}
		
		if(mMediaRecorder!=null){
			mMediaRecorder.release();
		}
		}catch(OutOfMemoryError error){
			cgt.jni.business.LogMgr.GetInstance().writeLog("OutOfMemoryError from  SpeakControl line 116");
		}catch (Exception ex){
			
		}
	}
	/**
	 * 录音完成回调函数
	 * @param path
	 */
	public void onRecordCompletion(String path){}
	/**
	 * 音頻播放完囘調函数
	 */
	public void onMediaCompletion() {
		// Toast.makeText(CaseUp.this, "completion", 0).show();
		m_microphone.setVisibility(View.VISIBLE);
		m_microphoneing.setVisibility(View.GONE);
		m_ckAudioPlay.setChecked(false);
		m_media_state.setText("就绪");
		m_ckAudio.setEnabled(true);
	};
	
	
	/**
	 * 开始播放
	 */
	public void play(){
		try {
			if(path!=null&&path.exists()&&path.canRead()){
				m_mediaPlayer=new MediaPlayer();
				m_mediaPlayer.setDataSource(path.getAbsolutePath());
				m_mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
					
					@Override
					public void onCompletion(MediaPlayer mp) {
						if(null!=mp){
							mp.release();
						}
						onMediaCompletion();
						
					}
				});
			//	m_mediaPlayer.reset();
				m_mediaPlayer.prepare();
				m_mediaPlayer.start();
				Log.e(TAG, path.getAbsolutePath()+" no exists  or  no canRead");
			}else{
				Log.e(TAG, "play path is null");
			}
		} catch (IllegalArgumentException e) {
			m_mediaPlayer.release();
			e.printStackTrace();
		} catch (IllegalStateException e) {
			m_mediaPlayer.release();
			e.printStackTrace();
		} catch (IOException e) {
			m_mediaPlayer.release();
			e.printStackTrace();
		}catch(OutOfMemoryError error){
			cgt.jni.business.LogMgr.GetInstance().writeLog("OutOfMemoryError from  SpeakControl line 167");
		}catch(Exception ex){
			cgt.jni.business.LogMgr.GetInstance().writeLog("Exception from  SpeakControl line 169");
		}
	}
	
	boolean flag = false;
	/**
	 * 弹出录音对话框
	 */
	public void speakDialogShow(){
		alertSoundBox.show();
		m_microphone.setVisibility(View.GONE);
//	//m_microphoneing.setVisibility(View.VISIBLE);

	m_media_state.setText("准备就绪");

	m_ckAudioPlay.setChecked(true);
	m_ckAudio.setChecked(false);
	m_microphone.setVisibility(View.VISIBLE);
	m_microphoneing.setVisibility(View.GONE);
	m_ckAudioPlay.setChecked(false);
	m_ckAudio.setEnabled(true);
//		if (flag) {
//			startRecord();
//			m_ckAudio.setChecked(true);
//			m_media_state.setText("录音中...");
//			flag = false;
//		} else {
////			//play();
////			m_microphone.setVisibility(View.GONE);
////			//m_microphoneing.setVisibility(View.VISIBLE);
////
////			m_media_state.setText("准备就绪");
////
////			m_ckAudioPlay.setChecked(true);
////			m_ckAudio.setChecked(false);
//			m_microphone.setVisibility(View.VISIBLE);
//			m_microphoneing.setVisibility(View.GONE);
//			m_ckAudioPlay.setChecked(false);
//			m_media_state.setText("就绪");
//			m_ckAudio.setEnabled(true);
//		}
	}
	
	public void speakDialogClose(){
		release();
		alertSoundBox.close();
	}
	/**
	 * 是否正在听你说话  是返回true  否则返回false
	 */
	public boolean isListening(){
		if (null != m_ckAudio && m_ckAudio.isChecked()) {
			return true;
		}
		return false;
	}
	/**
	 * 设置录音状态   true 为正在录音  false  结束录音
	 * @param flag
	 */
	public void setAudioState(boolean flag){
		if (null != m_ckAudio && m_ckAudio.isChecked()) {
			m_ckAudio.setChecked(flag);
		}
	}
	
	OnClickListener audioListener = new OnClickListener() {
		CheckBox ckb = null;

		@Override
		public void onClick(View v) {

			int id = v.getId();
			if (id == R.id.dialog_exit) {
				release();
				alertSoundBox.close();
				if (null != m_ckAudio && m_ckAudio.isChecked()) {
					m_ckAudio.setChecked(false);
				}
			} else if (id == R.id.ck_record) {
				ckb = (CheckBox) v;
				if (ckb.isChecked()) {
					startRecord();
					m_ckAudioPlay.setEnabled(false);
					m_ckAudioPlay.setChecked(false);

					m_microphone.setVisibility(View.GONE);
					m_microphoneing.setVisibility(View.VISIBLE);

					m_media_state.setText("录音中...");
					suspend();
				} else {
					stopRecord();
					m_ckAudioPlay.setEnabled(true);
					m_ckAudioPlay.setChecked(false);
					m_microphone.setVisibility(View.VISIBLE);
					m_microphoneing.setVisibility(View.GONE);

					m_media_state.setText("完毕");
				}
				ckb.setEnabled(false);
				// 录音操作间隔最小0.5秒
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						ckb.setEnabled(true);

					}
				}, 1500);
			} else if (id == R.id.ck_play) {
				ckb = (CheckBox) v;
				// Toast.makeText(CaseUp.this, "不"+ckb.isChecked(), 0).show();
				if (ckb.isChecked()) {
					play();
					m_microphone.setVisibility(View.GONE);
					m_microphoneing.setVisibility(View.VISIBLE);

					m_media_state.setText("播放中...");
				} else {
					suspend();
					m_microphone.setVisibility(View.VISIBLE);
					m_microphoneing.setVisibility(View.GONE);

					m_media_state.setText("完毕");

					m_ckAudio.setEnabled(true);
				}
			}

		}
	};
	
	

}

